package com.lxw.nonghe.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.annotation.RequiresPermission;
import com.lxw.nonghe.common.Result;
import com.lxw.nonghe.entity.CooperativeInstitution;
import com.lxw.nonghe.service.CooperativeInstitutionService;
import com.lxw.nonghe.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 农合经办机构控制器
 */
@RestController
@RequestMapping("/cooperativeInstitution")
@RequiresPermission("cooperativeInstitution:manage")
public class CooperativeInstitutionController {

    @Autowired
    private CooperativeInstitutionService cooperativeInstitutionService;

    @Autowired
    private LogUtils logUtils;

    @PostMapping("/create")
    public Result<Boolean> addInstitution(@RequestBody CooperativeInstitution institution) {
        if (institution == null) {
            logUtils.recordLog("农合经办机构管理", "新增机构", "失败", "机构信息不能为空");
            return Result.error("机构信息不能为空");
        }

        try {
            // 如果前端没有传递 createTime，则设置为当前时间
            if (institution.getCreateTime() == null) {
                institution.setCreateTime(new Date());
            }

            // 更新时间设置为当前时间
            institution.setUpdateTime(new Date());

            boolean result = cooperativeInstitutionService.save(institution);

            if (result) {
                // 重新获取以确保获取到数据库生成的ID
                CooperativeInstitution saved = cooperativeInstitutionService.getInstitutionByName(institution.getInstitutionName());
                logUtils.recordLog("农合经办机构管理", "新增机构", "成功",
                        "机构名称:" + saved.getInstitutionName() + ", 机构ID:" + saved.getInstitutionId());
                return Result.success("机构新增成功", true);
            } else {
                logUtils.recordLog("农合经办机构管理", "新增机构", "失败", "保存数据库失败");
                return Result.error("机构新增失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("农合经办机构管理", "新增机构", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/delete/{id}")
    public Result<Boolean> deleteInstitution(@PathVariable Integer id) {
        if (id == null) {
            logUtils.recordLog("农合经办机构管理", "删除机构", "失败", "机构ID不能为空");
            return Result.error("机构ID不能为空");
        }

        try {
            CooperativeInstitution institution = cooperativeInstitutionService.getById(id);
            boolean result = cooperativeInstitutionService.removeById(id);

            if (result) {
                logUtils.recordLog("农合经办机构管理", "删除机构", "成功",
                        "机构ID:" + id + ", 机构名称:" + (institution != null ? institution.getInstitutionName() : "未知"));
                return Result.success("机构删除成功", true);
            } else {
                logUtils.recordLog("农合经办机构管理", "删除机构", "失败", "机构ID不存在:" + id);
                return Result.error("机构删除失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("农合经办机构管理", "删除机构", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public Result<Boolean> updateInstitution(@RequestBody CooperativeInstitution institution) {
        if (institution == null || institution.getInstitutionId() == null) {
            logUtils.recordLog("农合经办机构管理", "更新机构", "失败", "机构ID不能为空");
            return Result.error("机构ID不能为空");
        }

        try {
            // 无论前端是否传递 updateTime，都设置为当前时间
            institution.setUpdateTime(new Date());

            boolean result = cooperativeInstitutionService.updateById(institution);

            if (result) {
                logUtils.recordLog("农合经办机构管理", "更新机构", "成功",
                        "机构ID:" + institution.getInstitutionId());
                return Result.success("机构更新成功", true);
            } else {
                logUtils.recordLog("农合经办机构管理", "更新机构", "失败",
                        "机构ID不存在:" + institution.getInstitutionId());
                return Result.error("机构更新失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("农合经办机构管理", "更新机构", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @GetMapping("/get/{id}")
    public Result<CooperativeInstitution> getInstitutionById(@PathVariable Integer id) {
        if (id == null) {
            logUtils.recordLog("农合经办机构管理", "查询机构", "失败", "机构ID不能为空");
            return Result.error("机构ID不能为空");
        }

        try {
            CooperativeInstitution institution = cooperativeInstitutionService.getById(id);
            if (institution != null) {
                return Result.success("机构查询成功", institution);
            } else {
                logUtils.recordLog("农合经办机构管理", "查询机构", "失败", "机构ID不存在:" + id);
                return Result.error("未找到该机构");
            }
        } catch (Exception e) {
            logUtils.recordLog("农合经办机构管理", "查询机构", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<IPage<CooperativeInstitution>> getInstitutionPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String institutionName,
            @RequestParam(required = false) String regionCode) {

        if (current < 1) current = 1;
        if (size < 1 || size > 100) size = 10;

        try {
            IPage<CooperativeInstitution> institutionPage =
                    cooperativeInstitutionService.getInstitutionPage(current, size, institutionName, regionCode);

            return Result.success("机构分页查询成功", institutionPage);
        } catch (Exception e) {
            logUtils.recordLog("农合经办机构管理", "分页查询机构", "失败", e.getMessage());
            return Result.error("分页查询异常: " + e.getMessage());
        }
    }

    @PostMapping("/query")
    public Result<Page<CooperativeInstitution>> queryInstitutions(
            @RequestBody CooperativeInstitution queryParam,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {

        if (current < 1) current = 1;
        if (size < 1 || size > 100) size = 10;

        try {
            Page<CooperativeInstitution> institutionPage =
                    cooperativeInstitutionService.queryInstitution(queryParam, current, size);

            return Result.success("机构条件查询成功", institutionPage);
        } catch (Exception e) {
            logUtils.recordLog("农合经办机构管理", "条件查询机构", "失败", e.getMessage());
            return Result.error("条件查询异常: " + e.getMessage());
        }
    }
}
